import math
from typing import List, Literal, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import not_, select, desc
from sqlalchemy import select, distinct, func, desc
from sqlalchemy.orm import joinedload
from app.models import Activity, ActivityCampus
from sqlalchemy.ext.asyncio import AsyncSession

from app.schemas.activity import AdminActivityCreate, AdminActivityRead, AdminActivityUpdate


class AdminActivityService:
    def __init__(self, db: AsyncSession):
        self.db = db
        pass

    async def create_activity(self, obj: AdminActivityCreate):
        models = obj.into()
        self.db.add_all(models)
        await self.db.commit()

    async def get_activity(self, page: int, size: int, filter: Optional[str] = None):
        stmt = select(Activity)
        stmt = stmt.order_by(desc(Activity.id)).limit(size).offset((page - 1) * size)
        result = await self.db.execute(stmt)
        result = result.scalars().all()
        return [AdminActivityRead.model_validate(i) for i in result]

    async def update_activity(self, obj: AdminActivityUpdate):
        model = await self.db.execute(select(Activity).filter(Activity.id == obj.id))
        model = model.scalar()
        if model is None:
            raise Exception("Activity not found")
        
        if obj.name is not None:
            model.name = obj.name
        if obj.activity_time is not None:
            model.activity_time = obj.activity_time
        if obj.additional_conditions is not None:
            model.additional_conditions = obj.additional_conditions
        if obj.content is not None:
            model.content = obj.content
        if obj.count_limit is not None:
            model.count_limit = obj.count_limit
        if obj.location is not None:
            model.location = obj.location
        if obj.submission_deadline is not None:
            model.submission_deadline = obj.submission_deadline
        if obj.poster is not None:
            model.poster = obj.poster
        if obj.type is not None:
            model.type = obj.type
        if obj.publisher is not None:
            model.publisher = obj.publisher
        if obj.campuses is not None:
            model.campuses = int(obj.campuses)  # 确保存储整数值
        
        await self.db.commit()
        return model

    async def delete_activity(self, id: int) -> bool:
        stmt = select(Activity).filter(Activity.id == id)
        result = await self.db.execute(stmt)
        model = result.scalar()
        if model is None:
            return False
        
        await self.db.delete(model)
        await self.db.commit()
        return True